<?php

namespace app\admin\controller;

use think\Db;
use think\Request;
use think\Exception;//事务处理
use app\admin\model\File;

class Procat extends Auth
{
    public function __construct(Request $request){
        $this->getChildIDdata = [];
        parent::__construct($request);
        $this->data = $request->param();
        $this->user_id = session('userid') == null ? 1 : session('userid');
        $this->lang = isset($this->data['lang']) && $this->data['lang'] ? $this->data['lang'] : is_lang();
    }


    // 产品类型list
    public function list(Request $request)
    {   
        $join = [
            ['multi_lang mu', 'zu.mkey = mu.mkey']
        ];
        // 按条件查找
        if(isset($this->data['searchText']) && $this->data['searchText']){  
            $searchTextWhere['mu.content'] = ['like', '%' . $this->data['searchText'] . '%'];
            $searchTextWhere['mu.mkey'] = ['like', '%procat%'];
            $searchTextWhere['mu.lang'] = $this->lang;

            $procate_data = getSearch('procat','zu',['zu.*,mu.content'],$searchTextWhere,$join,'zu.drank asc');
            $searchText = $this->data['searchText'];
        }else{
            $res = getSearch('procat','zu',['zu.*,mu.content'],['mu.lang'=>$this->lang],$join,'zu.drank asc');
            $procate_data =getTree($res);
            $searchText = '';
        }
        // 获取分页数据
        $returnData['size'] = count( $procate_data);
        if(isset($this->data['page']) && isset($this->data['limit'])){
            if($this->data['limit']*($this->data['page']-1) < $returnData['size']){
                $procate_data = array_slice($procate_data,$this->data['limit']*($this->data['page']-1),$this->data['limit']);
                $returnData['page'] = $this->data['page'];
            }
        }
        
        //  获取分类绑定的属性名称，获取多语言状态
        foreach ($procate_data as $k => $v) {
            $procate_data[$k]['is_hide'] = $v['status'] == 3 ? 'H' : '-';
            $procate_data[$k]['is_del'] = $v['status'] == 2 ? 'D' : '-';
            // $procate_data[$k]['public'] = $v['is_public'] == 1 ? lang('yes') : lang('no');
            // 获取属性名称并拼装字符串
            $cateIdWhere['procat_ids'] = ['like', '%' . $v['id'] . '%'];
            $cateIdWhere['mu.lang'] = $this->lang;
            $result = getSearch('proattr','zu',['zu.id,mu.content'],$cateIdWhere,$join,'zu.drank asc');
            if(!empty($result)){
                $procate_data[$k]['child'] = $result;
                $proAttrStr = '';
                foreach ($result as $resultkey => $resultvalue) {
                    $proAttrStr .= $resultvalue['content'].',';
                }
                $procate_data[$k]['proAttrStr'] = rtrim($proAttrStr,',');
            }else{
                $procate_data[$k]['proAttrStr'] = '';
            }
        }
        // dump($procate_data);die;
        $returnData['searchText'] = $searchText;
        if($request->isAjax()){
            $returnData['procate_data'] = $procate_data;
            $returnData['lang'] = isset($this->data['lang']) ? $this->data['lang'] : 'zh';
            $returnData['titleStr'] = lang('product_category');
            return json_encode($returnData);
        }else{
            return view('list',['procate_data'=>$procate_data,'searchText'=>$searchText]);    
            // return view('catelist');
        }
              
    }

    public function cateAdd()
    {   
        if($this->data['request'] == 'add'){
            $catedata = getMultiLangName('procat',['*'],'1=1','drank asc');
            $catedata =getTree($catedata);
            // dump($catedata);
            return view('cateadd',['title'=>lang('add'),'catedata'=>$catedata,'request'=>'add']);

        }else if($this->data['request'] == 'addChild'){

            if($this->data['id'] != 0){
                $addChild = getMultiLangName('procat',['*'],['id'=>$this->data['id']],'drank asc');
                $addChild=$addChild[0];
            }else{
                $addChild = '';
            }
            return view('cateadd',['title'=>'添加子级','addChild'=>$addChild,'request'=>'add']);

        }else if($this->data['request'] == 'insert'){

            unset($this->data['request']);
            // return $this->data;

            if(hasData('procat',['pid'=>$this->data['zh']['pclass'],'drank'=>$this->data['zh']['drank']])){
                $whereDrank = 'drank between '.($this->data['zh']['drank']).' and 99';
                $is_drank = changeDrank('procat',['pid'=>$this->data['zh']['pclass']],$whereDrank);
            }
            // return $this->data;
            // 新增 占位获取主键Id
            $dataInsert['pid'] = 0;
            $dataInsert['drank'] = $this->data['zh']['drank'];
            // 开启事务
            Db::startTrans();
                $cateId = insertData('procat',$dataInsert);
                if($cateId){
                    // foreach ($this->data as $k => $v) {
                    // 判断是否为空
                    if($this->data['zh']['clasname']['value'] == null){
                        Db::rollback();
                        return json_encode(array('status'=>2,'msg'=>lang('missing').' '.lang('product_category_name')));
                    }else{
                        // 判断当前语言下该内容是否存在
                        $has_value = hasData('multi_lang',['lang'=>is_lang(),'mkey'=>'%procat%','content'=>$this->data['zh']['clasname']['value']]);
                        if($has_value){
                            // Db::rollback();
                            return json_encode(array('status'=>3,'msg'=>lang('product_category').'->'.$this->data['zh']['clasname']['value'].' '.lang('already_exists')));
                        }else{
                            // 获取多语言分类，分别添加一样的的数据，后期进行编辑
                            $lang_cate = getLanguage($this->lang);
                            foreach ($lang_cate as $k => $v) {
                                $status = $this->data['zh']['status'] == '' ? 1 : $this->data['zh']['status'];
                                $ress = updateData('procat',['id'=>$cateId],['mkey'=>'procat_'.$cateId,'pid'=>$this->data['zh']['pclass'],'status'=>$status,'is_public'=>$this->data['zh']['general']]);
                                $multi_langData['mkey'] = 'procat_'.$cateId;
                                $multi_langData['lang'] = $v['code'];
                                $multi_langData['content'] = $this->data['zh']['clasname']['value'];
                                $res = insertData('multi_lang',$multi_langData);
                            }
                        }
                    }
                    // }
                    // return $multi_langData;
                    if($res){
                        // 提交事务
                        Db::commit();
                        return json_encode(array('status'=>1,'msg'=>lang('product').'->'.$this->data['zh']['clasname']['value'].' '.lang('added_successfully')));
                    }else{
                        Db::rollback();
                        return json_encode(array('status'=>0,'msg'=>lang('product').'->'.$this->data['zh']['clasname']['value'].' '.lang('add_failed')));
                    }
                    
                }
        }else{
            return json_encode(array('status'=>2,'msg'=>lang('improve_submission_data')));
        }
    }


    public function cateEdit(){

        if($this->data['request'] == 'edit'){
            // 所有分类数据
            $catedata = getMultiLangName('procat',['*'],'1=1','drank asc');
            $catedata =getTree($catedata);

            //当前ID 分类详情
            $detail = getMultiLangName('procat',['*'],['id'=>$this->data['id']],'drank asc');
            // dump($catedata);die;
            return view('cateadd',['request'=>'edit','title'=>lang('edit'),'catedata'=>$catedata,'editParent_id'=>$this->data['pid'],'detail'=>$detail[0]]);
        }else if($this->data['request'] == 'update'){
            unset($this->data['request']);
            // return $this->data;
            $res = $this->cateUpdate($this->data);
            return $res;
        }else{
            return json_encode(array('status'=>2,'msg'=>lang('improve_submission_data')));
        }
    }


    function cateUpdate($data){
        Db::startTrans();
        // try{
            foreach ($data as $k => $v) {
                // dump($k);die;
                if($v['pclass'] >= 0){
                    if(hasData('procat',['pid'=>$v['pclass'],'drank'=>$v['drank']])){
                        if($v['drank'] > $v['olddrank']){  
                            $whereDrank = 'drank between '.$v['olddrank'].' and '.$v['drank'];
                        }

                        if($v['drank'] < $v['olddrank']){
                            $whereDrank = 'drank between '.$v['drank'].' and '.($v['olddrank']-1);
                        }
                        // return $whereDrank;
                        // 是否需要从新排序
                        if($v['drank'] != $v['olddrank']){
                            $is_drank = changeDrank('procat',['pid'=>$v['pclass']],$whereDrank);
                        }
                    }

                    $res_a = updateData('procat',['id'=>$v['clasname']['id']],['pid'=>$v['pclass'],'status'=>$v['status'],'is_public'=>$v['general'],'drank'=>$v['drank']]);
                    if($res_a >= 0){
                        $res_b = updateData('multi_lang',['mkey'=>'procat_'.$v['clasname']['id'],'lang'=>$k],['content'=>$v['clasname']['value']]);
                        if($k == $this->lang){
                            $content = $v['clasname']['value'];
                        }
                        Db::commit();
                    }else{
                        return json_encode(array('status'=>0,'msg'=>lang('product_category').'->'.$v['clasname']['value'].' '.lang('edit_failed')));
                    }
                }else{
                    return json_encode(array('status'=>2,'msg'=>lang('improve_submission_data')));
                }
            }
            if($res_b >=0){
                Db::commit();
                return json_encode(array('status'=>1,'msg'=>lang('product_category').'->'.$content.' '.lang('edited_successfully')));
            }else{
                return json_encode(array('status'=>0,'msg'=>lang('product_category').'->'.$content.' '.lang('edit_failed')));
            }
        // }catch(\Exception $e){
        //     Db::rollback();
        //     return json_encode(array('status'=>500,'msg'=>lang('mysql_fail')));
        // }
    }


    //查看分类详情
    public function catedetail()
    {   
        if($this->data['id']){

            $data = getMultiLangName('procat',['*'],['id'=>$this->data['id']],'drank asc')[0];
            // dump($data);die;
            // 多语言状态

            $lang_cate = getLanguage();
            foreach ($lang_cate as $k => $v) {
                $data['is_hide_'.$v['code']] = $data['status'] == 3 ? lang('yes') : lang('no');
                $data['is_del_'.$v['code']] = $data['status'] == 2 ? lang('yes') : lang('no');
            }

            // $data['is_hide_en'] = $data['status'] == 3 ? getViewMultiLanguage('yes','en') : getViewMultiLanguage('no','en');
            // $data['is_del_en'] = $data['status'] == 2 ? getViewMultiLanguage('yes','en') : getViewMultiLanguage('no','en');

            // $data['is_hide_pt'] = $data['status'] == 3 ? getViewMultiLanguage('yes','pt') : getViewMultiLanguage('no','pt');
            // $data['is_del_pt'] = $data['status'] == 2 ? getViewMultiLanguage('yes','pt') : getViewMultiLanguage('no','pt');

            // 获取上一级数据
            if($data['pid'] > 0){
                $parent = getTreeParent('procat',['*'],['id'=>$data['pid']]);
            }else{
                $parent = [];
            }
            // dump($parent);die;

            // 属性名称数据
            $cateIdWhere['procat_ids'] = ['like', '%' . $this->data['id'] . '%'];
            $childAttr = getMultiLangName('proattr',['*'],$cateIdWhere,'drank asc');
            // dump($childAttr);die;

            // 子类数量
            $childCount = count($this->getChildID('procat',['id'],'1=1',$this->data['id']));
            // 产品数量
            $proCount = hasData('pro2cate',['procat_id'=>'procat_'.$this->data['id']]);
            return view('catedetail',['data'=>$data,'parent'=>$parent,'childAttr'=>$childAttr,'childCount'=>$childCount,'proCount'=>$proCount]);
        }else{
            return view('catedetail');
        }
    }

    // 获取当前类行下 所以能用的子级
    function getChildID($table,$field,$where,$pid=0)
    {   
        $_data = Db::name($table)
                    ->field($field)
                    ->where($where)
                    ->where('pid',$pid)
                    // ->fetchSql()
                    ->select();
                // return $_data;
        if(!empty( $_data)){
            foreach ($_data as $k => $v) {
                array_push($this->getChildIDdata,$v['id']);
                $res = $this->getChildID($table,$field,$where,$v['id']);
            }
        }
            return $this->getChildIDdata;
        
    }


    // 批量/单个删除
    public function batchDel()
    {
        return $this->changeStatus($this->data,$this->lang);
    }
    
    // 批量/单个恢复
    public function batchRestore()
    {
        return $this->changeStatus($this->data,$this->lang);
    }

    // 批量/单个清除
    public function batchClear()
    {
        return $this->changeStatus($this->data,$this->lang);
    }

    // 批量/单个隐藏
    public function batchHide()
    {
        return $this->changeStatus($this->data,$this->lang);
    }



    // 下架/批量下架，软删除/批量软删除，恢复/批量恢复，清除/批量清除
    public function changeStatus($data,$lang){
        if(!empty($data['id'])){  // 判断条件是否达成
            if($data['fun'] == 'update'){
                $updateData = ['status'=>$data['value']];

                Db::startTrans();
                    $content = '';
                    if(is_array($data['id'])){    

                        foreach ($data['id'] as $k => $v) {   
                            if($k < 3){
                                $content .= ','.getValue('multi_lang',['mkey'=>'procat_'.$v,'lang'=>$lang],'content');
                            }
                            if($k == 3){
                                $content .= '...';
                            }
                            if($data['value'] == 2){
                                $getChildIDWhere['status'] = ['in','1,3,4'];
                                $is_has = $this->getChildID($data['table'],['id'],$getChildIDWhere,$v);
                                if($is_has){
                                    return json_encode(array('status'=>2,'msg'=>lang("contains_sublevel_doesn't_allow_deletion")));
                                }
                            }
                            $res = updateData($data['table'],['id'=>$v],$updateData);
                        }
                    }else{

                        if($data['value'] == 2){
                            $getChildIDWhere['status'] = ['in','1,3,4'];
                            $is_has = $this->getChildID($data['table'],['id'],$getChildIDWhere,$data['id']);
                            if($is_has){
                                return json_encode(array('status'=>2,'msg'=>lang('failed_to_delete').lang("contains_sublevel_doesn't_allow_deletion")));
                            }
                        }
                        $res = updateData($data['table'],['id'=>$data['id']],$updateData);
                        $content .= getValue('multi_lang',['mkey'=>'procat_'.$data['id'],'lang'=>$lang],'content');
                    }
                    ltrim($content,',');
                    if($res >= 0){
                        Db::commit();
                        return json_encode(array('status'=>1,'msg'=>lang('product_category').'->'.$content.' '.lang(getViewMultiLanguage($data['value'])).' '.lang('successfully')));
                    }else{
                        return json_encode(array('status'=>0,'msg'=>lang('product_category').'->'.$content.' '.lang(getViewMultiLanguage($data['value'])).' '.lang('failed')));
                    }
            }else if($data['fun'] == 'deletes'){     // 清除
                // 是否批量清除
                if(is_array($data['id'])){    
                    $content = '';
                    foreach ($data['id'] as $k => $v) {  
                        // $res = $requestDel($v);
                        // return $res;
                        if($k < 3){
                            $content .= ','.getValue('multi_lang',['mkey'=>'procat_'.$v,'lang'=>$lang],'content');
                        }
                        if($k == 3){
                            $content .= '...';
                        }
                        $proattrRes = getDatas('procat',['*'],['id'=>$v]);
                        if(!empty($proattrRes)){
                            if($proattrRes[0]['status'] !=2){
                                return json_encode(array('status'=>2,'msg'=>$content.' 无法清除，状态不是回收状态'));
                            }

                            if($proattrRes[0]['is_public'] ==1){
                                return json_encode(array('status'=>2,'msg'=>$content.' '.lang('clear_failed').'通用分类，需先解除通用'));
                            }
                        }
                        Db::startTrans();
                        try{
                            $getChildIDWhere['status'] = ['in','1,3,4'];
                            $is_has = $this->getChildID($data['table'],['id'],$getChildIDWhere,$v);
                            if($is_has == []){  // 判断是否存在子级，或者非软删除状态子级 
                                // 删除旗下所有子级
                                $delData = $this->getChildID($data['table'],['id'],'1=1',$v);
                                array_push($delData, (int)$v);
                                foreach ($delData as $k1 => $v1) {
                                    // 判断当前分类Id是否绑定产品
                                    $has_pro = hasData('pro2cate',['procat_id'=>$v1]);
                                    if($has_pro){
                                        return json_encode(array('status'=>0,'msg'=>lang('product_category').'->'.$content.' '.lang('clear_failed').' '.lang('binding').' '.lang('product')));
                                    }else{
                                        $has_attrWhere = "find_in_set(".$v1.",procat_ids)";
                                        $has_attr = Db::name('proattr')->where($has_attrWhere)->select();
                                        if($has_attr) return json_encode(array('status'=>0,'msg'=>lang('product_category').' '.lang('clear_failed').' '.lang('binding_product_properties')));
                                        $res = deleteData($data['table'],['id'=>$v1]);
                                        if($res){
                                            $res1 = deleteData('multi_lang',['mkey'=>$data['table'].'_'.$v1]);
                                        }
                                    }
                                }
                                if($res){
                                    Db::commit();
                                }

                            }else{
                                return json_encode(array('status'=>2,'msg'=>lang('product_category').'->'.$content.' '.lang("contains_sublevel_doesn't_allow_deletion")));
                            }
                        }catch(\Exception $e){
                            Db::rollback();
                            return json_encode(array('status'=>3,'msg'=>$e));
                        }
                    }
                    ltrim($content,',');
                    if($res){
                        Db::commit();
                        return json_encode(array('status'=>1,'msg'=>lang('product_category').'->'.$content.' '.lang('cleared_successfully')));
                    }else{
                        Db::rollback();
                        return json_encode(array('status'=>0,'msg'=>lang('product_category').'->'.$content.' '.lang('clear_failed')));
                    }
                }else{

                        $proattrRes = getDatas('procat',['*'],['id'=>$data['id']]);
                        if(!empty($proattrRes)){
                            if($proattrRes[0]['status'] !=2){
                                return json_encode(array('status'=>2,'msg'=>'无法清除，状态不是回收状态'));
                            }

                            if($proattrRes[0]['is_public'] ==1){
                                return json_encode(array('status'=>2,'msg'=>lang('clear_failed').'通用属性，需先解除通用'));
                            }
                        }
                    Db::startTrans();
                        $getChildIDWhere['status'] = ['in','1,3,4'];
                        $is_has = $this->getChildID($data['table'],['id'],$getChildIDWhere,$data['id']);
                        $content = getValue('multi_lang',['mkey'=>'procat_'.$data['id'],'lang'=>$lang],'content');
                        if($is_has == []){  // 判断是否存在子级，或者非软删除状态子级 
                            // 删除旗下所有子级
                            $delData = $this->getChildID($data['table'],['id'],'1=1',$data['id']);
                            array_push($delData, (int)$data['id']);
                            
                            foreach ($delData as $k1 => $v1) {
                                // 判断当前分类Id是否绑定产品
                                $has_pro = hasData('pro2cate',['procat_id'=>$v1]);
                                if($has_pro){
                                    return json_encode(array('status'=>0,'msg'=>lang('product_category').' '.lang('clear_failed').' '.lang('binding').' '.lang('product')));
                                }else{
                                    if($k1 < 4){
                                        $content .= ','.getValue('multi_lang',['mkey'=>'procat_'.$v1,'lang'=>$lang],'content');
                                    }
                                    if($k1 = 4){
                                        $content .= '...';
                                    }
                                    $has_attrWhere = "find_in_set(".$v1.",procat_ids)";
                                    $has_attr = Db::name('proattr')->where($has_attrWhere)->select();
                                    if($has_attr) return json_encode(array('status'=>0,'msg'=>lang('product_category').' '.lang('clear_failed').' '.lang('binding_product_properties')));
                                    $res = deleteData($data['table'],['id'=>$v1]);
                                    if($res){
                                        $res1 = deleteData('multi_lang',['mkey'=>$data['table'].'_'.$v1]);
                                    }
                                }
                            }
                            ltrim($content,',');
                            if($res1){
                                Db::commit();
                                return json_encode(array('status'=>1,'msg'=>lang('product_category').'->'.$content.' '.lang('cleared_successfully')));
                            }else{
                                Db::rollback();
                                return json_encode(array('status'=>0,'msg'=>lang('product_category').'->'.$content.' '.lang('clear_failed')));
                            }

                        }else{
                            return 12;
                            return json_encode(array('status'=>2,'msg'=>lang('product_category').'->'.$content.' '.lang("contains_sublevel_doesn't_allow_deletion")));
                        }
                }
            }
        }else{
            return json_encode(array('status' => 3,'msg'=>'请勾选需要操作的产品分类' ));
        }

    }

    // 删除fun
    function requestDel($id){
        Db::startTrans();
        try{
            $getChildIDWhere['status'] = ['in','1,3,4'];
            $has_attrWhere = "find_in_set(".$id.",procat_ids)";
            $has_attr = Db::name('proattr')->where($has_attrWhere)->select();
            if($has_attr) return json_encode(array('status'=>0,'msg'=>lang('product_category').' '.lang('clear_failed').' '.lang('binding_product_properties')));
            $is_has = $this->getChildID('procat',['id'],$getChildIDWhere,$id);
            if(!empty($is_has) ){  // 判断是否存在子级，或者非软删除状态子级 
                // 删除旗下所有子级
                $delData = $this->getChildID('procat',['id'],'1=1',$id);
                array_push($delData, (int)$id);
                $content = '';
                foreach ($delData as $k1 => $v1) {
                    // 判断当前分类Id是否绑定产品
                    $has_pro = hasData('pro2cate',['procat_id'=>$v1]);

                    if($has_pro){
                        return json_encode(array('status'=>2,'msg'=>lang("contains_sublevel_doesn't_allow_deletion")));
                    }else{
                        if($k1 < 4){
                            $content .= ','.getValue('multi_lang',['mkey'=>'procat_'.$v1,'lang'=>$lang],'content');
                        }
                        if($k1 = 4){
                            $content .= '...';
                        }
                        $res = deleteData('procat',['id'=>$v1]);
                        if($res){
                            $content .= getValue('multi_lang',['mkey'=>'procat_'.$v1,'lang'=>$lang],'content');
                            $res1 = deleteData('multi_lang',['mkey'=>'procat_'.$v1]);
                        }
                    }
                }
                ltrim($content,',');
                if($res1){
                    Db::commit();
                    return json_encode(array('status'=>1,'msg'=>lang('product_category').'->'.$content.' '.lang('cleared_successfully')));
                }else{
                    Db::rollback();
                    return json_encode(array('status'=>0,'msg'=>lang('product_category').'->'.$content.' '.lang('clear_failed')));
                }

            }else{
                return json_encode(array('status'=>2,'msg'=>lang('product_category').'->'.$content.' '.lang("contains_sublevel_doesn't_allow_deletion")));
            }
        }catch(\Exception $e){
            Db::rollback();
            return json_encode(array('status'=>3,'msg'=>$e));
        }
    }


}
